package marlon.smsbatcheditor.activity;

import java.util.List;

import marlon.smsbatcheditor.R;
import marlon.smsbatcheditor.db.RuleDAO;
import marlon.smsbatcheditor.model.Rule;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.os.Bundle;

/**
 * 
 * @author marlonyao<yaolei135@gmail.com>
 */
public class ShortcutActivity extends Activity {
	private List<Rule> rules;
	private RuleDAO ruleDAO;
	
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setVisible(false);
        
        ruleDAO = new RuleDAO(this);
        rules = ruleDAO.findAll();
        
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Select Rule");
        builder.setAdapter(new RulesAdapter(this, android.R.layout.select_dialog_item, rules), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Intent shortcutIntent = new Intent(getApplicationContext(), PreviewActivity.class);
			    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			    Rule rule = rules.get(which);
				shortcutIntent.putExtra("rule_id", rule.getId());

				ShortcutIconResource iconResource = Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.drawable.icon);
				Intent intent = new Intent();
		        intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
		        intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, rule.getName());
		        intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
		   		
		   		setResult(RESULT_OK, intent);
		   		finish();
			}
		});
        
        AlertDialog dlg = builder.create();
        dlg.setOnDismissListener(new DialogInterface.OnDismissListener() {
			@Override
			public void onDismiss(DialogInterface dialog) {
				setResult(RESULT_CANCELED);
				finish();
			}
		});
        dlg.show();
    }
}
